package com.lk.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lk.common.Result;
import com.lk.common.DeleteRequest;
import com.lk.common.ErrorCode;
import com.lk.exception.BusinessException;
import com.lk.model.domain.Team;
import com.lk.model.domain.User;
import com.lk.model.domain.UserTeam;
import com.lk.model.dto.TeamQuery;
import com.lk.model.request.TeamAddRequest;
import com.lk.model.request.TeamJoinRequest;
import com.lk.model.request.TeamQuitRequest;
import com.lk.model.request.TeamUpdateRequest;
import com.lk.model.vo.TeamUserVO;
import com.lk.model.vo.TeamVo;
import com.lk.service.TeamService;
import com.lk.service.UserService;
import com.lk.service.UserTeamService;
import com.lk.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 队伍接口
 *
 */
@RestController
@RequestMapping("/team")
//@CrossOrigin(origins = {"http://localhost:3000","http://keyl1001.top","http://www.keyl1001.top"})
@Slf4j
public class TeamController {

    @Resource
    private UserService userService;

    @Resource
    private TeamService teamService;

    @Resource
    private UserTeamService userTeamService;

    @Resource
    private AliOssUtil aliOssUtil;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 创建队伍
     * @param teamAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public Result<Long> addTeam(@RequestBody MultipartFile file,TeamAddRequest teamAddRequest,HttpServletRequest request) {
        if (teamAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        if (file == null ){
            return Result.error(ErrorCode.PARAMS_ERROR,"请正确选择头像");
        }

        //获取头像路径
        String avatarUrl=teamService.getAvatarUrl(file,request);
        teamAddRequest.setAvatarUrl(avatarUrl);

        User loginUser = userService.getLoginUser(request);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest, team);
        long teamId = teamService.addTeam(team, loginUser);
        return Result.success(teamId);
    }

    /**
     * 修改队伍信息
     *
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/update")
    public Result<Boolean> updateTeam(@RequestBody MultipartFile file,TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) {
        if (teamUpdateRequest == null && file ==null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"没有任何更新");
        }
        if (file != null){
            Team team = teamService.getById(teamUpdateRequest.getId());
            String url = team.getAvatarUrl();

            int i = url.lastIndexOf('/');
            String substring = url.substring(i + 1);

            //删除之前的头像
            aliOssUtil.delete(substring);

            String avatarUrl = teamService.getAvatarUrl(file, request);
            teamUpdateRequest.setAvatarUrl(avatarUrl);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.updateTeam(teamUpdateRequest, loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新失败");
        }
        //删除redis中该队伍的用户缓存
        String key = "CodePartner:team:getUsersByTeamId:"+teamUpdateRequest.getId();
        redisTemplate.delete(key);
        //写入新的更新后的缓存
        redisTemplate.opsForValue().set("CodePartner:team:getUsersByTeamId:%s", teamUpdateRequest.getId());
        return Result.success(true);
    }

    @GetMapping("/get")
    public Result<Team> getTeamById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(id);
        if (team == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return Result.success(team);
    }


    /**
     * 根据条件搜索队伍
     *
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list")
    public Result<List<TeamUserVO>> listTeams(TeamQuery teamQuery, HttpServletRequest request) {
        //查询条件为空，抛出自定义的参数异常
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean isAdmin = userService.isAdmin(request);
        // 1、根据条件查来询队伍列表
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, isAdmin);
        //获取这些查出来的队伍的id
        final List<Long> teamIdList = teamList.stream().map(TeamUserVO::getId).collect(Collectors.toList());


        // 2、找出当前用户已经加入的队伍
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        try {
            User loginUser = userService.getLoginUser(request);
            userTeamQueryWrapper.eq("userId", loginUser.getId());
            userTeamQueryWrapper.in("teamId", teamIdList);

            //根据用户id和队伍id进行匹配，找到已加入的队伍
            List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
            // 用户已加入的队伍 id 集合
            Set<Long> hasJoinTeamIdSet = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());

            //遍历按符合条件查找到的队伍,在已加入的队伍设置hasJoin为true
            teamList.forEach(team -> {
                boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
                team.setHasJoin(hasJoin);
            });
        } catch (Exception e) {
        }

        // 3、查询已加入队伍的人数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        if(teamIdList.size()>0){
            userTeamJoinQueryWrapper.in("teamId", teamIdList);
        }
        List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
        // 队伍 id => 加入这个队伍的用户列表  =>  select * from user_team group by teamId
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));

        teamList.forEach(team -> team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()));

        return Result.success(teamList);
    }


    // todo 查询分页
    @GetMapping("/list/page")
    public Result<Page<Team>> listTeamsByPage(TeamQuery teamQuery) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        BeanUtils.copyProperties(teamQuery, team);
        Page<Team> page = new Page<>(teamQuery.getPageNum(), teamQuery.getPageSize());
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        Page<Team> resultPage = teamService.page(page, queryWrapper);
        return Result.success(resultPage);
    }

    @PostMapping("/join")
    public Result<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
        if (teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.joinTeam(teamJoinRequest, loginUser);
        return Result.success(result);
    }

    /**
     * 退出队伍
     * @param teamQuitRequest
     * @param request
     * @return
     */
    @PostMapping("/quit")
    public Result<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
        if (teamQuitRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.quitTeam(teamQuitRequest, loginUser);
        return Result.success(result);
    }

    /**
     * 删除（解散）队伍
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public Result<Boolean> deleteTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.deleteTeam(id, loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
        }
        return Result.success(true);
    }


    /**
     * 获取我创建的队伍
     *
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list/my/create")
    public Result<List<TeamUserVO>> listMyCreateTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        boolean isAdmin = userService.isAdmin(request);

        //获取当前登录用户
        User loginUser = userService.getLoginUser(request);

        //把当前登录用户id设置为查询条件teamQuery中的队伍创建人id
        teamQuery.setUserId(loginUser.getId());
        //根据查询条件拼接（创建人id），查询我创建的队伍，这里用TeamUserVo用于返回
        List<TeamUserVO> teamList = teamService.listMyCreateAndJoinTeams(teamQuery, isAdmin);

        //获取我创建的队伍的id
        final List<Long> teamIdList = teamList.stream().map(TeamUserVO::getId).collect(Collectors.toList());

        //如果没有查询到我创建的队伍，则直接返回
        if (teamIdList.isEmpty()){
            return Result.success(teamList);
        }

        //根据队伍id查询出队伍已加入的人数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        userTeamJoinQueryWrapper.in("teamId", teamIdList);
        //找到我创建的队伍，以及队伍-成员对象UserTeam
        List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);

        //一个队伍id对应多个UserTeam（一个队伍可能有多个成员），需要把UserTeam分组
        // 队伍 id => 加入这个队伍的用户列表  =>  select * from user_team group by teamId
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));

        //遍历要返回的teamList（Vo对象）,设置每个队伍的已加入人数
        teamList.forEach(team -> team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()));
        return Result.success(teamList);
    }


    /**
     * 获取我加入的队伍
     *
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list/my/join")
    public Result<List<TeamUserVO>> listMyJoinTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //获取当前登录用户
        User loginUser = userService.getLoginUser(request);

        //根据userId获取对应的user-team关系
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", loginUser.getId());
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);

        //没有查询到我加入的队伍，则直接返回
        if (userTeamList.isEmpty()) {
            return Result.success(new ArrayList<>());
        }

        //将我加入的每个队伍的id放到一个list中
        List<Long> idList = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toList());

        //idList作为条件查询出所有我加入的队伍
        teamQuery.setIdList(idList);
        List<TeamUserVO> teamList = teamService.listMyCreateAndJoinTeams(teamQuery, false);

        //根据队伍id查询出队伍已加入的人数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        userTeamJoinQueryWrapper.in("teamId", idList);
        userTeamList = userTeamService.list(userTeamJoinQueryWrapper);

        //一个队伍id对应多个UserTeam（一个队伍可能有多个成员），需要把UserTeam分组
        // 队伍 id => 加入这个队伍的用户列表  =>  select * from user_team group by teamId
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));

        //遍历要返回的teamList（Vo对象）,设置每个队伍的已加入人数
        teamList.forEach(team -> team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()));
        //将我加入的队伍设置成已加入
        teamList.forEach(team -> team.setHasJoin(true));
        return Result.success(teamList);

  /*      // 取出不重复的队伍 id
        // teamId userId
        // 1, 2
        // 1, 3
        // 2, 3
        // result
        // 1 => 2, 3
        // 2 => 3
        Map<Long, List<UserTeam>> listMap = userTeamList.stream()
                .collect(Collectors.groupingBy(UserTeam::getTeamId));

        //将我加入的每个队伍的id放到一个list中
        List<Long> idList = new ArrayList<>(listMap.keySet());
        //idList作为条件查询出所有我加入的队伍
        teamQuery.setIdList(idList);
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, true);
        //将我加入的队伍设置成已加入
        teamList.forEach(team -> team.setHasJoin(true));
        //设置队伍已加入的人数
        teamList.forEach(team -> team.setHasJoinNum(listMap.getOrDefault(team.getId(), new ArrayList<>()).size()));
        return Result.success(teamList);*/

    }


    /**
     * 根据队伍id获取用户列表（展示队伍详情）
     *
     * @param teamId
     * @param request
     * @return
     */
    @GetMapping("/{teamId}")
    public Result<TeamVo> getUsersByTeamId(@PathVariable("teamId") Long teamId, HttpServletRequest request) {
        if (teamId == null || teamId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该用户暂未加入队伍");
        }
        TeamVo teams = teamService.getUsersByTeamId(teamId, request);
        return Result.success(teams);
    }

}

